package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.mapper.*;
import com.itheima.reggie.service.OrderDetailService;
import com.itheima.reggie.service.OrderService;
import com.itheima.reggie.service.ShoppingCartService;
import com.itheima.reggie.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Transactional
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired(required = false)
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired(required = false)
    private UserMapper userMapper;
    @Autowired(required = false)
    private AddressBookMapper addressBookMapper;
    @Autowired(required = false)
    private OrderDetailMapper orderDetailMapper;
    @Autowired(required = false)
    private OrderMapper orderMapper;

    @Autowired
    private UserService userService;

    @Autowired
    private OrderDetailService orderDetailService;

    /**
     * 提交订单，并订单详情;
     *
     * @param orders
     */
    @Override
    public void submit(Orders orders) {
        //获得当前用户id
        Long userId = BaseContext.getCurrentId();
        //查询当前用户的购物车数据
        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ShoppingCart::getUserId, userId);
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.selectList(lqw);
        if (shoppingCarts == null || shoppingCarts.size() == 0) {
            throw new CustomException("购物车为空，不能下单");
        }
        //查询用户数据
        User user = userMapper.selectById(userId);

        //查询地址数据
        Long addressBookId = orders.getAddressBookId();
        AddressBook addressBook = addressBookMapper.selectById(addressBookId);
        if (addressBook == null) {
            throw new CustomException("用户地址信息有误，不能下单");
        }
        //订单号
        long orderId = IdWorker.getId();

        //组装订单表
        //1.1 先补充orders的数据
        orders.setId(IdWorker.getId());
        //1.1.1 设置number， 数量
        orders.setNumber(orders.getId() + "");
//        orders.setNumber(UUID.randomUUID().toString().replace("-",""));
        //1.1.2 设置订单的状态： 1待付款，2待派送，3已派送，4已完成，5已取消
        orders.setStatus(1);
        //1.1.3 设置用户id
        orders.setUserId(user.getId());
        //1.1.4 设置地址的id  不需要设置，因为页面已经提供了
        //1.1.5 设置提交订单时间
        orders.setOrderTime(LocalDateTime.now());
        //1.1.6 设置付款时间
        orders.setCheckoutTime(LocalDateTime.now());
        //1.1.7 设置付款方式 不需要设置，因为页面已经提供了
        //1.1.8 设置总金额  不需要设置，因为页面已经提供了
        //1.1.9 设置备注 不需要设置，因为页面已经提供了
        //1.1.10 提交订单的用户用户名
        orders.setUserName(user.getName());

        orders.setPhone(addressBook.getPhone());
        //1.1.12 收货人的地址 = 省份  + 城市 + 地区 + 详细地址
        orders.setAddress(
                (addressBook.getProvinceName() != null ? addressBook.getProvinceName() : "") +
                        (addressBook.getCityName() != null ? addressBook.getCityName() : "") +
                        (addressBook.getDistrictName() != null ? addressBook.getDistrictName() : "") +
                        (addressBook.getDetail() != null ? addressBook.getDetail() : "")
        );
        //1.1.13 收货人的名字
        orders.setConsignee(addressBook.getConsignee());

        int row = 0;

        //往订单详细表填充数据
        for (ShoppingCart shoppingCart : shoppingCarts) {
            //2.3 遍历一次购物车对象，就创建一个订单详情对象
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setId(IdWorker.getId());
            BeanUtils.copyProperties(shoppingCart, orderDetail);
            //2.5 设置属于哪个订单
            orderDetail.setOrderId(orders.getId());
            row += orderDetailMapper.insert(orderDetail);

        }
        //添加订单表
        int row2 = orderMapper.insert(orders);
        //3. 如果订单都已经添加好了，那么就情况购物车
        if (row2 > 0 && row == shoppingCarts.size()) {
            shoppingCartService.clean();
        }
    }

    /**
     * 后端订单分页查询，可以与前端分页查询合并
     *
     * @param page
     * @param pageSize
     * @param number
     * @param beginTime
     * @param endTime
     * @return
     */
    @Override
    public IPage<OrdersDto> fandPage(int page, int pageSize, String number, String beginTime, String endTime) {
        Page<Orders> ordersPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        lqw.eq(number != null, Orders::getNumber, number);
        lqw.gt(beginTime != null, Orders::getOrderTime, beginTime);
        lqw.lt(endTime != null, Orders::getOrderTime, endTime);
        orderMapper.selectPage(ordersPage, lqw);

        Page<OrdersDto> ordersDtoPage = new Page<>();
        //设置总数
        ordersDtoPage.setTotal(ordersPage.getTotal());
        List<OrdersDto> list = ordersPage.getRecords().stream().map((order) -> {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(order, ordersDto);
            Long userId = order.getUserId();
            User user = userMapper.selectById(userId);
            if (user.getName() == null) {
                String consigneeName = order.getConsignee();
                ordersDto.setUserName(consigneeName);
            } else {
                ordersDto.setUserName(user.getName());
            }

            return ordersDto;
        }).collect(Collectors.toList());
        ordersDtoPage.setRecords(list);
        return ordersDtoPage;
    }

    /**
     * 更改状态值
     *
     * @param orders
     * @return
     */

    @Override
    public int updateStatus(Orders orders) {

        return orderMapper.updateById(orders);
    }

    /**
     * 前端查询最新的订单，查询历史订单，其实可以与后端的分页查询合并，
     *
     * @param page     起始索引
     * @param pageSize 一次查多小条
     * @return
     */
    @Override
    public IPage fandOrders(Integer page, Integer pageSize) {
        Page<Orders> ordersPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        lqw.orderByDesc(Orders::getOrderTime);
        //查询出ordersPage的数据
        orderMapper.selectPage(ordersPage, lqw);

        Page<OrdersDto> ordersDtoPage = new Page<>();
        //设置总数
        ordersDtoPage.setTotal(ordersPage.getTotal());
        List<OrdersDto> list = ordersPage.getRecords().stream().map((order) -> {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(order, ordersDto);
            Long userId = order.getUserId();
            User user = userMapper.selectById(userId);
            if (user.getName() == null) {
                String consigneeName = order.getConsignee();
                ordersDto.setUserName(consigneeName);
            } else {
                ordersDto.setUserName(user.getName());
            }
            //查询订单下所有的菜品
            Long orderId = order.getId();
            //根据orderId查询订单详情
            List<OrderDetail> orderDetails = orderDetailService.findByOrderId(orderId);
            ordersDto.setOrderDetails(orderDetails);
            return ordersDto;
        }).collect(Collectors.toList());
        ordersDtoPage.setRecords(list);
        return ordersDtoPage;
    }
}
